package com.example.ttsapp

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.text.Editable
import android.text.SpannableString
import android.text.Spannable
import android.text.TextWatcher
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.util.Locale
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContracts
import android.os.Environment
import android.provider.Settings
import android.net.Uri
import android.widget.ScrollView

class MainActivity : AppCompatActivity() {
    private lateinit var textInput: EditText
    private lateinit var wordCount: TextView
    private lateinit var playButton: Button
    private lateinit var pauseButton: Button
    private lateinit var saveButton: Button
    private lateinit var textToSpeech: TextToSpeech
    private lateinit var scrollView: ScrollView
    
    private var isPlaying = false
    private var currentReadPosition = 0  // 当前朗读位置
    private var lastPlayedText = ""      // 上次播放的文本
    private var pausedPosition = 0       // 暂停位置
    private var isPaused = false         // 是否处于暂停状态
    private var currentPosition = 0  // 当前播放位置
    private var currentText = ""     // 当前播放的文本
    private var isNewText = false       // 是否是新文本

    // 修改 Activity Result 注册
    private val checkTTSResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            // TTS数据已安装
        } else {
            // TTS数据未安装，尝试安装
            val installIntent = Intent()
            installIntent.action = TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA
            startActivity(installIntent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        initViews()
        initTTS()
        setupListeners()
        checkPermissions()
    }

    private fun initViews() {
        textInput = findViewById(R.id.textInput)
        wordCount = findViewById(R.id.wordCount)
        playButton = findViewById(R.id.playButton)
        pauseButton = findViewById(R.id.pauseButton)
        saveButton = findViewById(R.id.saveButton)
        scrollView = findViewById(R.id.scrollView)  // 初始化 scrollView
        val scrollTopButton = findViewById<Button>(R.id.scrollTopButton)

        // 设置文本变化监听器
        textInput.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                wordCount.text = "字数：${s?.length ?: 0}"
            }
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })

        // 添加返回顶部按钮点击事件
        scrollTopButton.setOnClickListener {
            scrollView.smoothScrollTo(0, 0)
        }
    }

    private fun initTTS() {
        try {
            val ttsIntent = Intent()
            ttsIntent.action = TextToSpeech.Engine.ACTION_CHECK_TTS_DATA
            checkTTSResult.launch(ttsIntent)

            textToSpeech = TextToSpeech(this) { status ->
                if (status == TextToSpeech.SUCCESS) {
                    try {
                        // 设置语言
                        var result = textToSpeech.setLanguage(Locale("zh", "CN"))
                        if (result == TextToSpeech.LANG_MISSING_DATA || 
                            result == TextToSpeech.LANG_NOT_SUPPORTED) {
                            result = textToSpeech.setLanguage(Locale.CHINESE)
                        }
                        if (result == TextToSpeech.LANG_MISSING_DATA || 
                            result == TextToSpeech.LANG_NOT_SUPPORTED) {
                            result = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE)
                        }
                        
                        if (result == TextToSpeech.LANG_MISSING_DATA || 
                            result == TextToSpeech.LANG_NOT_SUPPORTED) {
                            // 如果语言包缺失，提示用户安装
                            val installIntent = Intent()
                            installIntent.action = TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA
                            startActivity(installIntent)
                            Toast.makeText(this, "请安装中文语音包", Toast.LENGTH_LONG).show()
                            return@TextToSpeech
                        }
                        
                        // 设置语速和音量
                        textToSpeech.setSpeechRate(1.0f)
                        textToSpeech.setPitch(1.0f)
                        
                        // 设置默认的播放监听器
                        setPlaybackProgressListener()
                        
                    } catch (e: Exception) {
                        Toast.makeText(this, "TTS初始化异常：${e.message}", 
                            Toast.LENGTH_LONG).show()
                    }
                } else {
                    val message = when (status) {
                        TextToSpeech.ERROR -> "错误"
                        TextToSpeech.STOPPED -> "已停止"
                        -1 -> "没有找到合适的TTS引擎"
                        else -> status.toString()
                    }
                    Toast.makeText(this, "TTS初始化失败：$message", Toast.LENGTH_LONG).show()
                }
            }
        } catch (e: Exception) {
            Toast.makeText(this, "TTS系统异常：${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    // 添加新方法：设置播放监听器
    private fun setPlaybackProgressListener() {
        textToSpeech.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                if (utteranceId == "messageId") {
                    runOnUiThread {
                        isPlaying = true
                        playButton.isEnabled = false
                        pauseButton.isEnabled = true
                    }
                }
            }

            override fun onDone(utteranceId: String?) {
                if (utteranceId == "messageId") {
                    runOnUiThread {
                        isPlaying = false
                        if (isNewText) {
                            currentPosition = 0
                            isNewText = false
                        }
                        playButton.isEnabled = true
                        pauseButton.isEnabled = false
                    }
                }
            }

            override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) {
                if (utteranceId == "messageId") {
                    runOnUiThread {
                        // 只在非暂停状态下更新位置
                        if (!isPlaying) return@runOnUiThread
                        currentPosition += start
                    }
                }
            }

            override fun onError(utteranceId: String?) {
                if (utteranceId == "messageId") {
                    runOnUiThread {
                        isPlaying = false
                        playButton.isEnabled = true
                        pauseButton.isEnabled = false
                        Toast.makeText(this@MainActivity, "播放出错", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    private fun setupListeners() {
        playButton.setOnClickListener {
            startSpeaking()
        }

        pauseButton.setOnClickListener {
            stopSpeaking()
        }

        saveButton.setOnClickListener {
            saveToMp3()
        }
    }

    private fun startSpeaking() {
        val text = textInput.text.toString()
        if (text.isEmpty()) {
            Toast.makeText(this, "请先输入文字", Toast.LENGTH_SHORT).show()
            return
        }

        if (!::textToSpeech.isInitialized) {
            Toast.makeText(this, "TTS尚未初始化", Toast.LENGTH_SHORT).show()
            return
        }

        try {
            // 检查是否是新文本
            isNewText = text != currentText
            if (isNewText) {
                currentPosition = 0
                currentText = text
                scrollView.post {
                    scrollView.smoothScrollTo(0, 0)
                }
            }

            // 从当前位置开始播放
            val remainingText = text.substring(currentPosition)
            val params = Bundle()
            params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "messageId")
            
            val result = textToSpeech.speak(remainingText, TextToSpeech.QUEUE_FLUSH, params, "messageId")
            if (result == TextToSpeech.SUCCESS) {
                isPlaying = true
                playButton.isEnabled = false
                pauseButton.isEnabled = true
            } else {
                Toast.makeText(this, "播放失败", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "播放出错：${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun stopSpeaking() {
        if (textToSpeech.isSpeaking) {
            textToSpeech.stop()
            isPlaying = false
            playButton.isEnabled = true
            pauseButton.isEnabled = false
        }
    }

    private fun saveToMp3() {
        val text = textInput.text.toString()
        if (text.isEmpty()) {
            Toast.makeText(this, "请先输入文字", Toast.LENGTH_SHORT).show()
            return
        }

        try {
            // 创建进度对话框
            val progressDialog = androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("正在保存")
                .setMessage("正在生成音频文件，请稍候...")
                .setCancelable(false)
                .create()
            
            // 显示进度对话框
            progressDialog.show()

            // 使用外部存储目录
            val directory = File(Environment.getExternalStorageDirectory(), "文本转语音")
            if (!directory.exists()) {
                val success = directory.mkdirs()
                if (!success) {
                    progressDialog.dismiss()
                    Toast.makeText(this, "创建目录失败", Toast.LENGTH_SHORT).show()
                    return
                }
            }

            val fileName = "tts_${System.currentTimeMillis()}.wav"
            val file = File(directory, fileName)

            val params = Bundle()
            params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "saveFile")

            // 临时设置保存监听器
            val saveListener = object : UtteranceProgressListener() {
                override fun onStart(utteranceId: String?) {
                    if (utteranceId == "saveFile") {
                        runOnUiThread {
                            progressDialog.setMessage("开始生成音频文件...")
                        }
                    }
                }

                override fun onDone(utteranceId: String?) {
                    if (utteranceId == "saveFile") {
                        runOnUiThread {
                            // 关闭进度对话框
                            progressDialog.dismiss()
                            
                            // 显示保存成功对话框
                            androidx.appcompat.app.AlertDialog.Builder(this@MainActivity)
                                .setTitle("已经保存成功")
                                .setMessage("保存路径：${file.absolutePath}\n文件名：$fileName")
                                .setPositiveButton("确定") { _, _ ->
                                    // 恢复播放监听器
                                    setPlaybackProgressListener()
                                }
                                .show()
                        }
                    }
                }

                override fun onError(utteranceId: String?) {
                    if (utteranceId == "saveFile") {
                        runOnUiThread {
                            // 关闭进度对话框
                            progressDialog.dismiss()
                            Toast.makeText(baseContext, "保存失败", Toast.LENGTH_SHORT).show()
                            // 恢复播放监听器
                            setPlaybackProgressListener()
                        }
                    }
                }

                override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) {
                    // 更新进度信息
                    runOnUiThread {
                        val progress = if (end > 0) (start.toFloat() / end * 100).toInt() else 0
                        progressDialog.setMessage("正在生成音频文件...\n进度：$progress%")
                    }
                }
            }

            // 设置保存监听器
            textToSpeech.setOnUtteranceProgressListener(saveListener)

            val result = textToSpeech.synthesizeToFile(text, params, file, "saveFile")
            if (result != TextToSpeech.SUCCESS) {
                progressDialog.dismiss()
                Toast.makeText(this, "保存失败：错误码 $result", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "保存失败：${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 及以上
            if (!Environment.isExternalStorageManager()) {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6.0 到 Android 10
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ),
                    1
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            if (grantResults.isNotEmpty() && 
                grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "需要存储权限才能保存音频文件", 
                    Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onDestroy() {
        if (::textToSpeech.isInitialized) {
            textToSpeech.stop()
            textToSpeech.shutdown()
        }
        super.onDestroy()
    }
} 